﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer.Model.Services;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Repositories;

using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Services.Concrete;
using DataAccess.Repositories;
using DataAccess.Services;

namespace intecnologia.Admin
{
    public partial class EditNews : System.Web.UI.Page
    {
        protected string _pageMode;

        private INewsRepository _newsRepository = new NewsRepository();
        private ISessionService _sessionService = new SessionService();
        private ITwitterService _tweeterService = new TwitterService();

        private BusinessLayer.Model.Entities.News _newsToAddorEdit;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_sessionService.SessionExpired())
                Response.Redirect("~/Admin/Default.aspx");

            _pageMode = Request.QueryString["edit"] == "true" ? "edit" : "add";

            if (_pageMode == "edit")
            {
                _newsToAddorEdit = _newsRepository.FetchByID(new Guid(Request.QueryString["id"]));

                if (!IsPostBack)
                    LoadNewsDetails();
            }

            else if (_pageMode == "add")
                _newsToAddorEdit = new BusinessLayer.Model.Entities.News();
                
        }

        private void LoadNewsDetails()
        {
            tbTitle.Text = _newsToAddorEdit.Title;
            tbDescription.Text = _newsToAddorEdit.Description;
            newsEditor.Content = _newsToAddorEdit.Content;
        }

        protected void btnSubmitChanges_Click(object sender, EventArgs e)
        {
            UpdateNews();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ExitEdit();
        }

        private void UpdateNews()
        {               
            _newsToAddorEdit.Title = tbTitle.Text;
            _newsToAddorEdit.Description = tbDescription.Text;
            _newsToAddorEdit.Content = newsEditor.Content;

            
            if (_pageMode == "edit")
                _newsRepository.UpdateOnSubmit(_newsToAddorEdit);

            else if (_pageMode == "add")
            {
                _newsRepository.InsertOnSubmit(_newsToAddorEdit);
                
                //hacer que el post en twitter sea opcional
                if (cbPostInTwitter.Checked)
                    _tweeterService.PostNews(_newsToAddorEdit);
            }
            _newsRepository.SubmitChanges();

            ExitEdit();
        }

        private void ExitEdit()
        {
            Response.Redirect("~/Admin/News.aspx");
        }
    }
}
